<template>
  <div class="app-container">
    <el-form ref="form" :model="searchForm" inline label-width="80px" label-suffix=":">
      <el-form-item label="用户名">
        <el-input v-model="searchForm.userName"></el-input>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input v-model="searchForm.phoneNumber"></el-input>
      </el-form-item>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button type="success" @click="handleAdd">新增</el-button>
    </el-form>
    <el-table :data="tableData" style="width: 100%" border>
      <el-table-column prop="user_name" label="用户名"></el-table-column>
      <el-table-column prop="user_phone" label="手机号"></el-table-column>
      <el-table-column prop="user_role" label="角色">
        <template v-if="roleList.length" slot-scope="scope">
          <el-tag v-for="item in scope.row.user_role" :key="item">{{ roleList.find(role => role.role_name === item).role_description }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建日期">
        <template slot-scope="scope">
          <div>{{ formatTime(scope.row.create_time) }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="date" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination :total="total" :current-page.sync="currentPage" @current-change="currentChange" background layout="total, prev, pager, next, jumper"></el-pagination>
    <el-dialog title="用户详情" :visible.sync="dialogVisible" width="500px" :before-close="handleClose">
      <el-form ref="form" :model="dialogForm" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-if="editType === 'add'" v-model="dialogForm.userName"></el-input>
          <span v-else>{{ dialogForm.userName }}</span>
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="dialogForm.phoneNumber"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-select
            v-model="dialogForm.roles"
            multiple
            collapse-tags>
            <el-option v-for="item in roleList" :key="item.role_id" :label="item.role_description" :value="item.role_name"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUserList, addUser, editUser, deleteUser } from '@/api/user'
import { getRoleList } from '@/api/role'
export default {

  data() {
    return {
      editType: '',
      dialogVisible: false,
      total: 0,
      currentPage: 1,
      searchForm: {
        userName: '',
        phoneNumber: ''
      },
      dialogForm: {
        userName: '',
        phoneNumber: '',
        roles: [],
        id: ''
      },
      tableData: [],
      roleList: [],
      rules: {
        userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        phoneNumber: [{ required: true, message: '请输入手机号', trigger: 'blur' }, { required: true, validator: this.phoneValidator }],
        roles: [{ required: true, message: '请选择角色', trigger: 'change' }]
      }
    }
  },
  mounted() {
    this.getRoles()
    this.getData()
  },
  methods: {
    handleSearch() {
      this.currentPage = 1
      this.getData()
    },
    handleEdit(row) {
      this.editType = 'edit'
      this.dialogForm.userName = row.user_name
      this.dialogForm.phoneNumber = row.user_phone
      this.dialogForm.roles = row.user_role
      this.dialogForm.id = row.user_id
      this.dialogVisible = true

    },
    handleAdd(row) {
      this.editType = 'add'
      this.dialogForm.userName = ''
      this.dialogForm.phoneNumber = ''
      this.dialogForm.roles = []
      this.dialogVisible = true

    },
    async getData() {
      const params = {
        page: this.currentPage,
        ...this.searchForm
      }
      const res = await getUserList(params)
      if(res.code === 0) {
        this.tableData = res.data
        this.total = res.total
      }
    },
    async confirm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const { userName, phoneNumber, roles } = this.dialogForm
          const params = { userName, phoneNumber, roles }
          let requestUrl
          if (this.editType === 'edit') {
            // 编辑
            params.id = this.dialogForm.id
            requestUrl = editUser
          } else if (this.editType === 'add') {
            // 新增
            params.password = '123456' // 默认密码
            requestUrl = addUser
          }
          const res = await requestUrl(params)
          if (res.code === 0) {
            this.$message({
              type: 'success',
              message: this.editType === 'edit' ? '修改成功' : '新增成功'
            })
            this.handleClose()
            this.getData()
          }
        }
      })
    },
    handleClose() {
      this.dialogVisible = false
      this.dialogForm.userName = ''
      this.dialogForm.phoneNumber = ''
      this.dialogForm.roles = []
      this.dialogForm.id = ''
      this.editType = ''
      setTimeout(() => this.$refs.form.clearValidate(), 500)
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await deleteUser({
          id: row.user_id
        })
        if (res.code === 0) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }
        this.getData()

      }).catch(() => {})
    },
    currentChange() {
      this.getData();
    },
    async getRoles() {
      const params = {
        page: 1,
        roleDesc: '',
        roleName: ''
      }
      const res = await getRoleList(params)
      if(res.code === 0) {
        this.roleList = res.data
      }
    },
    phoneValidator(rule, value, callback) {
      if (value.length !== 11 || !(/^\d+$/.test(value))) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
  }
}
</script>

